<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>在线问诊</title>
    <link rel="stylesheet" href="./element-ui/index.css">
    <style>
        .chat-container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
        }

        .chat-box {
            height: 400px;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
            background: #f8f9fa;
        }

        .message {
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
            max-width: 70%;
        }

        .message.sent {
            background: #409EFF;
            color: white;
            margin-left: auto;
        }

        .message.received {
            background: #67C23A;
            color: white;
        }

        .message.system {
            background: #909399;
            color: white;
            text-align: center;
        }

        .user-list-item {
            cursor: pointer;
            padding: 12px;
            transition: all 0.3s;
        }

        .user-list-item:hover {
            background-color: #ecf5ff;
        }

        .unread-badge {
            margin-left: 8px;
        }

        .online-users {
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div id="app">
    <el-container class="chat-container">
        <el-main>
            <el-card>
                <div slot="header">
                    <span v-if="plainUsername">正在咨询：{{ plainUsername }}</span>
                    <span v-else>在线用户列表</span>
                    <el-button
                            @click="openConnection"
                            type="primary"
                            size="small"
                            style="float: right;"
                            :disabled="!!plainUsername">
                        {{ plainUsername ? '已连接' : '开始咨询' }}
                    </el-button>
                </div>

                <div v-if="plainUsername">
                    <el-scrollbar class="chat-box" wrap-class="scrollbar-wrapper">
                        <div v-for="message in chatHistory[plainUsername]"
                             :key="message.id"
                             :class="['message', message.system ? 'system' : '', message.fromName === username ? 'sent' : 'received']">
                            <div><strong>{{ message.fromName }}：</strong>{{ message.message }}</div>
                            <div style="font-size: 12px; margin-top: 5px;">{{ message.timestamp }}</div>
                        </div>
                    </el-scrollbar>

                    <el-input
                            v-model="messageInput"
                            placeholder="输入咨询内容..."
                            @keyup.enter.native="sendMessage">
                        <el-button
                                slot="append"
                                @click="sendMessage"
                                icon="el-icon-s-promotion"
                                type="primary">
                            发送
                        </el-button>
                    </el-input>
                </div>

                <div v-else class="online-users">
                    <el-collapse accordion>
                        <el-collapse-item title="当前在线用户">
                            <el-menu>
                                <el-menu-item
                                        v-for="user in connectedUsers"
                                        :key="user"
                                        @click="selectUser(user)"
                                        class="user-list-item">
                                    <span>{{ user }}</span>
                                    <el-badge
                                            v-if="unreadMessages[user]"
                                            class="unread-badge"
                                            is-dot />
                                </el-menu-item>
                            </el-menu>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </el-card>
        </el-main>
    </el-container>
</div>

<script src="./vue/vue.js"></script>
<script src="./element-ui/index.js"></script>
<script src="./axios/axios.min.js"></script>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                username: localStorage.getItem('username') || 'user_' + Math.random().toString(36).substr(2, 5),
                socket: null,
                plainUsername: null,
                messageInput: '',
                chatHistory: {},
                connectedUsers: [],
                unreadMessages: {},
                messageId: 0
            }
        },
        methods: {
            openConnection() {
                this.socket = new WebSocket(`ws://localhost:8000/chat/${this.username}`);

                this.socket.onopen = () => {
                    this.$message.success('连接成功');
                };

                this.socket.onmessage = (event) => {
                    const message = JSON.parse(event.data);
                    this.handleIncomingMessage(message);
                    this.scrollToBottom();
                };

                this.socket.onclose = () => {
                    this.$message.warning('连接已关闭');
                    window.location.href = 'http://localhost:8000/static/home.html';
                    this.resetConnection();
                };

                this.socket.onerror = (error) => {
                    window.location.href = 'http://localhost:8000/static/home.html';
                    this.$message.error(`连接错误: ${error}`);
                };
            },

            handleIncomingMessage(message) {
                if (message.system) {
                    this.handleSystemMessage(message);
                } else {
                    this.handleChatMessage(message);
                }
            },

            handleSystemMessage(message) {
                if (message.message && !this.connectedUsers.includes(message.message)) {
                    this.connectedUsers.push(message.message);
                    this.$set(this.chatHistory, message.message, []);
                }
            },

            handleChatMessage(message) {
                if (!this.chatHistory[message.fromName]) {
                    this.$set(this.chatHistory, message.fromName, []);
                }

                const newMessage = {
                    ...message,
                    id: this.messageId++,
                    timestamp: new Date().toLocaleTimeString(),
                    unread: true
                };

                this.chatHistory[message.fromName].push(newMessage);

                if (message.fromName !== this.plainUsername) {
                    this.$set(this.unreadMessages, message.fromName, true);
                }
            },

            sendMessage() {
                if (this.messageInput && this.plainUsername) {
                    const messageObj = {
                        toName: this.plainUsername,
                        message: this.messageInput,
                        timestamp: new Date().toLocaleTimeString()
                    };

                    this.socket.send(JSON.stringify(messageObj));

                    this.chatHistory[this.plainUsername].push({
                        ...messageObj,
                        fromName: this.username,
                        id: this.messageId++,
                        system: false,
                        unread: false
                    });

                    this.messageInput = '';
                    this.unreadMessages[this.plainUsername] = false;
                    this.scrollToBottom();
                }
            },

            selectUser(user) {
                this.plainUsername = user;
                this.unreadMessages[user] = false;
            },

            scrollToBottom() {
                this.$nextTick(() => {
                    const container = document.querySelector('.scrollbar-wrapper');
                    if (container) {
                        container.scrollTop = container.scrollHeight;
                    }
                });
            },

            resetConnection() {
                this.plainUsername = null;
                this.chatHistory = {};
                this.connectedUsers = [];
                this.unreadMessages = {};
            }
        },
        beforeDestroy() {
            if (this.socket) {
                this.socket.close();
            }
        }
    });
</script>
</body>
</html>